package org.ucn.dmaa0914.gruppe6.gui;

import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JTable;
import javax.swing.JButton;

import java.awt.Component;

import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import org.ucn.dmaa0914.gruppe6.CustomerCtr;
import org.ucn.dmaa0914.gruppe6.EmployeeCtr;
import org.ucn.dmaa0914.gruppe6.Item;
import org.ucn.dmaa0914.gruppe6.ItemCtr;
import org.ucn.dmaa0914.gruppe6.Order;
import org.ucn.dmaa0914.gruppe6.OrderCtr;

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class OrderView extends JPanel {
	private JTable partOrderTable;
	private DefaultTableModel model;
	private int orderId;
	private JLabel lblTotal;
	private JLabel lblEmployee;
	private JLabel lblCustomer;
	private JLabel lblIsCompleted;

	/**
	 * Create the panel.
	 */
	public OrderView() {
		model = new DefaultTableModel();
		model.setColumnIdentifiers(new String[] {"Barcode", "Title", "Price", "Amount", "Subtotal"});
		
		setLayout(new BorderLayout(0, 0));
		
		partOrderTable = new JTable() {
	        public boolean isCellEditable(int row, int column) {                
	                return false;               
	        };
	    };
	    
		partOrderTable.setModel(model);
		
		JScrollPane scrollPane = new JScrollPane(partOrderTable);
		add(scrollPane, BorderLayout.CENTER);
		
		JPanel panel = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel.getLayout();
		flowLayout.setAlignment(FlowLayout.LEFT);
		add(panel, BorderLayout.SOUTH);
		
		JButton btnComplete = new JButton("Complete Order");
		btnComplete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if( !OrderCtr.getInstance().endOrder(orderId) )
				{
					JOptionPane.showMessageDialog(OrderView.this, "Could not complete order. Check that you are logged in and the payment succeeded.");
				}
				else
				{
					MainWindow.getInstance().updateViews();
				}
			}
		});
		btnComplete.setToolTipText("Completes the order and marks it as paid.");
		panel.add(btnComplete);
		
		Component horizontalStrut = Box.createHorizontalStrut(20);
		panel.add(horizontalStrut);
		
		JButton btnRemove = new JButton("Remove");
		btnRemove.setToolTipText("Remove the given amount of items from the part order.");
		panel.add(btnRemove);
		
		JButton btnAdd = new JButton("Add");
		btnAdd.setToolTipText("Adds the selected item the given amount of times.");
		panel.add(btnAdd);
		
		JLabel lblAmount = new JLabel("Amount:");
		panel.add(lblAmount);
		
		JSpinner spinAmount = new JSpinner();
		spinAmount.setToolTipText("Amount of items to add or remove");
		spinAmount.setModel(new SpinnerNumberModel(1, 1, 999999, 1));
		panel.add(spinAmount);
		
		Component horizontalStrut_1 = Box.createHorizontalStrut(20);
		panel.add(horizontalStrut_1);
		
		lblTotal = new JLabel("Total:");
		panel.add(lblTotal);
		
		JPanel panel_1 = new JPanel();
		add(panel_1, BorderLayout.NORTH);
		
		lblEmployee = new JLabel("Employee:");
		panel_1.add(lblEmployee);
		
		Component horizontalStrut_2 = Box.createHorizontalStrut(20);
		panel_1.add(horizontalStrut_2);
		
		lblCustomer = new JLabel("Customer:");
		panel_1.add(lblCustomer);
		
		Component horizontalStrut_3 = Box.createHorizontalStrut(20);
		panel_1.add(horizontalStrut_3);
		
		lblIsCompleted = new JLabel("Is Completed:");
		panel_1.add(lblIsCompleted);

		btnRemove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				OrderCtr.getInstance().removePartOrder(orderId, ItemCtr.getInstance().getCurrentItem(), ((Integer)spinAmount.getValue()).intValue());
				setOrder(OrderCtr.getInstance().find(orderId).getId());
			}
		});
		
		btnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				OrderCtr.getInstance().addPartOrder(orderId, ItemCtr.getInstance().getCurrentItem(), ((Integer)spinAmount.getValue()).intValue());
				setOrder(OrderCtr.getInstance().find(orderId).getId());
			}
		});
		
		partOrderTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
				Order o = OrderCtr.getInstance().find(orderId);
				if( o != null && e.getFirstIndex() < o.getPartOrders().size() )
				{
					ItemCtr.getInstance().setCurrentItem(o.getPartOrders().get(e.getFirstIndex()).getItem().getId());
				}
			}
		});
		
	}

	public void setOrder(int orderId)
	{
		Order o = OrderCtr.getInstance().find(orderId);
		
		if( o == null )
		{
			model.setRowCount(0);
			lblCustomer.setText("");
			lblEmployee.setText("");
			lblIsCompleted.setText("");
			lblTotal.setText("");
			return;
		}
		
		String currency = "";
		double total = 0.0;
		model.setRowCount(o.getPartOrders().size());
		for( int i = 0; i < o.getPartOrders().size(); ++i )
		{
			Item item = o.getPartOrders().get(i).getItem();
			
			model.setValueAt(item.getBarcode(), i, 0);
			model.setValueAt(item.getTitle(), i, 1);
			
			String formattedPrice = String.format("%s %.2f", item.getCurrency(), item.getPrice());
			model.setValueAt(formattedPrice, i, 2);
			model.setValueAt(o.getPartOrders().get(i).getAmount(), i, 3);
			
			double subTotal = OrderCtr.getInstance().getSubTotal(o.getId(), i);
			String formattedSubTotal = String.format("%s %.2f", item.getCurrency(), subTotal);
			model.setValueAt(formattedSubTotal, i, 4);
			total += subTotal;
			currency = item.getCurrency();
		}
		model.fireTableDataChanged();
		this.orderId = o.getId();
		
		lblCustomer.setText("Customer: " + CustomerCtr.getInstance().format(o.getCustomer()));
		lblEmployee.setText("Employee: " + EmployeeCtr.getInstance().format(o.getEmployee()));
		lblIsCompleted.setText("Is Completed: " + String.valueOf(o.isPaid()));
		lblTotal.setText("Total: " + String.format("%s %.2f", currency, total));
		
		partOrderTable.setBackground(o.isPaid() ? Color.LIGHT_GRAY : Color.WHITE);
	}
}
